package com.wuage.infrastructure.utils;

import com.google.common.collect.Maps;
import com.google.gson.*;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.time.DateUtils;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.*;

/**
 * @author Shynin
 */
public class OpenGsonWrapper {
    public static final GsonBuilder GSON_BUILDER;

    public static final Gson GSON;
    public static final TimeZone GMT = TimeZone.getTimeZone("CTT");
    private final static DateFormat EN_US_FORMAT
            = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US);
    private final static DateFormat LOCAL_FORMAT
            = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT);

    static {
        GSON_BUILDER = new GsonBuilder()
                .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
                    try {
                        try {
                            return new Date(json.getAsLong());
                        } catch (Exception e) {
                            return DateUtils.parseDate(json.getAsString(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
                        }
                    } catch (ParseException e) {
                        return deserializeToDate(json.getAsString());
                    }
                })
                .registerTypeAdapter(Long.class, (JsonDeserializer<Long>) (json, typeOfT, context) -> {
                    try {
                        return json.getAsLong();
                    }catch (Exception e){
                        return null;
                    }
                })
                .registerTypeAdapter(Integer.class, (JsonDeserializer<Integer>) (json, typeOfT, context) -> {
                    try {
                        return json.getAsInt();
                    }catch (Exception e){
                        return null;
                    }
                })
                .disableHtmlEscaping();
        GSON = GSON_BUILDER.create();
    }

    private static synchronized Date deserializeToDate(String json) {
        try {
            return LOCAL_FORMAT.parse(json);
        } catch (ParseException ignored) {
        }
        try {
            return EN_US_FORMAT.parse(json);
        } catch (ParseException ignored) {
        }
        try {
            return ISO8601Utils.parse(json, new ParsePosition(0));
        } catch (ParseException e) {
            throw new JsonSyntaxException(json, e);
        }
    }

    /**
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        return GSON.toJson(obj);
    }

    /**
     * @param json
     * @param typeToken
     * @param <T>
     * @return
     * @throws JsonSyntaxException
     */
    public static <T> T fromJson(String json, TypeToken<T> typeToken) throws JsonSyntaxException {
        return GSON.fromJson(json, typeToken.getType());
    }

    /**
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     * @throws JsonSyntaxException
     */
    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {
        return GSON.fromJson(json, classOfT);
    }

    /**
     *
     */
    static class LinkedTreeMapDeserializer implements JsonDeserializer<LinkedTreeMap> {
        @Override
        public LinkedTreeMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            LinkedTreeMap resultMap = new LinkedTreeMap();
            JsonObject jsonObject = json.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
            return resultMap;
        }
    }

    /**
     *
     */
    static class TreeMapDeserializer implements JsonDeserializer<TreeMap> {
        @Override
        public TreeMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            TreeMap resultMap = new TreeMap();
            JsonObject jsonObject = json.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
            return resultMap;
        }
    }

    /**
     *
     */
    static class HashMapDeserializer implements JsonDeserializer<HashMap> {

        @Override
        public HashMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            HashMap resultMap = Maps.newHashMap();
            JsonObject jsonObject = json.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
            return resultMap;
        }
    }

    /**
     *
     */
    static class MapDeserializer implements JsonDeserializer<Map> {
        @Override
        public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            Map resultMap = new LinkedTreeMap<>();
            JsonObject jsonObject = json.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
            return resultMap;
        }
    }

    static class ListDeserializer implements JsonDeserializer<List> {
        @Override
        public List deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            List list = new ArrayList<>();
            JsonArray jsonArray = json.getAsJsonArray();
            for (JsonElement jsonElement : jsonArray) {
                list.add(jsonElement);
            }
            return list;
        }
    }

}
